#ifndef SERVERSTRUCT_H
#define SERVERSTRUCT_H

#include "./common/SDS.h"
#include "./common/YXNet.h"
#include "./common/YXThreadPool.h"
#include "./common/cJSON.h"

#define SERVER_DEFAULT_HOST              "127.0.0.1"
#define SERVER_DEFAULT_PORT              9999
#define SERVER_DEFAULT_MAX_CLIENTS       1024
#define SERVER_DEFAULT_THREAD_POOL_SIZE  5
#define SERVER_DEFAULT_CONNETION_TIMEOUT 20000
#define EVENTLOOP_FDSET_INCR             100

#define FILE_RESOURCE_PATH_PREFIX "../data"

#define CLIENT_STATUS_CONNECTED    1
#define CLIENT_STATUS_BUSY         2
#define CLIENT_STATUS_DISCONNECTED 3

#define HTTP_TEMP_INPUT_BUFFER_SIZE        1024 * 2 /* 一般用于暂存请求和响应的行和头 */
#define HTTP_REQUEST_BODY_BUFFER_INIT_SIZE 1024 * 4

// #define HTTP_REQUEST_BODY_MAX_LENGTH 1024 * 1024 * 10
#define HTTP_REQUEST_LINE_MAX_LENGTH         512
#define HTTP_REQUEST_METHOD_MAX_LENGTH       6
#define HTTP_REQUEST_PATH_MAX_LENGTH         256
#define HTTP_REQUEST_FULL_PATH_MAX_LENGTH    HTTP_REQUEST_PATH_MAX_LENGTH + 10
#define HTTP_REQUEST_TOKEN_MAX_LENGTH        256
#define HTTP_REQUEST_CONTENT_TYPE_MAX_LENGTH 128

#define HTTP_RESPONSE_SYNC  1
#define HTTP_RESPONSE_ASYNC 2

#define HTTP_RESPONSE_BODY_BUFFER_INIT_SIZE 1024 * 10

#define HTTP_REQUEST_STATE_PARSE_LINE      1
#define HTTP_REQUEST_STATE_PARSE_HEADER    2
#define HTTP_REQUEST_STATE_PARSE_BODY      3
#define HTTP_REQUEST_STATE_PARSE_COMPLETED 4

#define ROUTE_DEFAULT_STATE 0

typedef LinkedList *Headers;

typedef struct {
    char *key;
    char *value;
} Header;

typedef struct {
    int    state;
    int    route_state;
    sds    method;
    sds    path;
    int    content_length;
    sds    token;
    sds    content_type;
    int    bodypos;
    sds    body;
    void*  parsed_data;
} Request;

typedef struct Client Client;

typedef struct Response {
    int     type;
    int     (*callback)(Client *client);
    int     staus;
    char   *staus_title;
    Headers headers;
    sds     content_type;
    int     content_length;
    int     bodypos;
    sds     body;
} Response;

typedef struct Client {
    int       auth;
    int       fd;
    int       bufpos;
    sds       input_buffer;
    Request  *request;
    Response *response;
    long long last_send_time;
    Client   *prev;
    Client   *next;
} Client;

typedef struct ClientList {
    Client *head;
    int     size;
} ClientList;

typedef struct {
    int             fd;
    int             connection_timeout;
    EventLoop      *el;
    ClientList     *client_list;
    pthread_mutex_t clients_mutex;
    char           *client_status;
    ThreadPool     *thread_pool;
} Server;

#endif // SERVERSTRUCT_H
